import React, {useEffect} from 'react'
import {Button, Card, Form, Input , message} from 'antd';
import style from "../index.module.css"
import {
  postAddHosRequest,
  getHosMsgFromIdReq,
  putHosMsgRequest
} from "@api/hospital/hospitalSet"
import type {
  postAddHosPramsType,
  putHosPramsType
} from "@api/hospital/model/hospitalSetTypes"
import {useNavigate, useParams} from "react-router-dom";

export default function AddOrUpdateHos() {
  const navigate = useNavigate()
  const {id} = useParams()
  const [form] = Form.useForm()
  console.log('id',id)
  // 3.根据id获取判断是路由跳转的对象并获取数据
  useEffect(()=>{
    if (id){
      const getHosHandle =async () =>{
        const re = await getHosMsgFromIdReq(id)
        // console.log('result',re)
        form.setFieldsValue(re)
      }
      getHosHandle()
    }
  })
  //1.添加医院信息请求
  const addHosHandle = async (FieldValue: putHosPramsType) => {
    //根据id判断是添加数据还是修改数据
    if (!id){
      await postAddHosRequest(FieldValue)
      message.success('添加医院数据成功！')
    }else {
      await putHosMsgRequest({
        ...FieldValue,
        id
      })
      message.success('修改医院数据成功！')

    }
    navigate("/syt/hospital/hospitalSet")
  }
  //2.返回上一级
  const goBackHandle = () => {
    navigate(-1)
  }




  return (
    <Card>
      <Form
        form = {form}
        name="control-hooks"
        onFinish={addHosHandle}
      >

        <Form.Item name="hosname" label='医院名称：' rules={[{required: true}]}>
          <Input placeholder='请输入医院名称'/>
        </Form.Item>
        <Form.Item name="hoscode" label='医院编号：' rules={[{required: true}]}>
          <Input placeholder='请输入医院编号'/>
        </Form.Item>
        <Form.Item name="apiUrl" label='api基础路径：' rules={[{required: true}]}>
          <Input placeholder='请输入api基础路径'/>
        </Form.Item>
        <Form.Item name="contactsName" label='联系人姓名：' rules={[{required: true}]}>
          <Input placeholder='请输入联系人姓名'/>
        </Form.Item>
        <Form.Item name="contactsPhone" label='联系人手机：' rules={[{required: true}]}>
          <Input placeholder='请输入联系人手机' maxLength={11}/>
        </Form.Item>

        <Form.Item>
          <Button type="primary" htmlType="submit" className={style.mr}>
            提交
          </Button>
          <Button type="default" onClick={goBackHandle}>
            返回
          </Button>
        </Form.Item>
      </Form>
    </Card>
  )
}